package org.lxw.stock;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Calendar;
import java.util.Date;

public class LC5FileBlock {
	final ByteBuffer bb1;
	Date time = null;

	public LC5FileBlock(byte[] bs) {
		bb1 = ByteBuffer.wrap(bs);
		bb1.order(ByteOrder.LITTLE_ENDIAN);
	}

	public Date getDate() {
		if (time == null) {
			short t = bb1.getShort(0);
			int t1 = t & 0x07ff;
			Calendar calendar = Calendar.getInstance();
			calendar.set((t >>> 11) + 2008, t1 / 100 - 1, t1 % 100);
			calendar.set(Calendar.HOUR_OF_DAY, (bb1.getShort(2)) / 60);
			calendar.set(Calendar.MINUTE, (bb1.getShort(2)) % 60);
			calendar.set(Calendar.SECOND, 0);
			time = calendar.getTime();
		}
		return time;
	}

	public float getOpen() {
		return get(bb1.getFloat(4));
	}

	public float getLow() {
		return get(bb1.getFloat(8));
	}

	public float getHigh() {
		return get(bb1.getFloat(12));
	}

	public float getClose() {
		return get(bb1.getFloat(16));
	}

	public int getTurnover() {
		return (int) (bb1.getFloat(20));
	}

	public int getVolume() {
		return bb1.getInt(24);
	}

	@Override
	public String toString() {
		return getDate().toLocaleString() + "," + getOpen() + "," + getLow()
				+ "," + getHigh() + "," + getClose() + "," + getTurnover()
				+ "," + getVolume();
	}

	private float get(float f) {
		float t = (int) ((f + 0.00001f) * 10000f);
		return t / 10000f;
	}
}